package com.qiaoba.file.ftp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.file.core.FileCore;
import com.qiaoba.api.file.entity.vo.FileUploadVO;
import com.qiaoba.api.file.util.FileUtil;
import com.qiaoba.common.base.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * FTP 文件服务实现
 *
 * @author ailanyin
 * @date 2023-09-26 14:36:52
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FtpFileServiceImpl implements FileCore {

    @Value("${ftp.nginxUrl}")
    private String nginxUrl;

    private final FTPClient ftpClient;

    @Override
    public FileUploadVO upload(String bucketName, String filename, Long size, InputStream inputStream) {
        try {
            String path = "/" + bucketName + "/" + DateUtil.format(new Date(), "yyyy/MM/dd");
            // 创建目录
            createDir(path);
            // 设置存储对象名称
            String objectName = path + "/" + UUID.randomUUID().toString() + "." + FileUtil.getExtension(filename);
            // 上传文件
            upload(objectName, inputStream);
            FileUploadVO vo = new FileUploadVO();
            vo.setUrl(nginxUrl + objectName);
            vo.setFileName(filename);
            vo.setPath(objectName);
            return vo;
        } catch (Exception e) {
            throw new ServiceException("FTP上传失败, 异常: " + e.getMessage());
        } finally {
            IoUtil.close(inputStream);
        }
    }

    @Override
    public void delete(String bucketName, String path) {
        try {
            ftpClient.deleteFile(path);
        } catch (IOException e) {
            throw new ServiceException("FTP删除失败, 异常: " + e.getMessage());
        }
    }


    private synchronized void createDir(String path) {
        try {
            // 判断文件目录是否存在
            if (ftpClient.changeWorkingDirectory(path)) {
                // 切换到根目录
                ftpClient.changeWorkingDirectory("/");
                return;
            }
            for (String str : StrUtil.split(path, File.separator)) {
                if (StrUtil.isNotBlank(str)) {
                    // 说明目录不存在, 创建目录
                    if (!ftpClient.changeWorkingDirectory(str)) {
                        ftpClient.makeDirectory(str);
                        ftpClient.changeWorkingDirectory(str);
                    }
                }
            }
            // 切换到根目录
            ftpClient.changeWorkingDirectory("/");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void upload(String objectName, InputStream inputStream) {
        try {
            boolean result = ftpClient.storeFile(objectName, inputStream);
            if (!result) {
                throw new ServiceException("FTP文件上传失败！");
            }
        } catch (IOException e) {
            throw new ServiceException("FTP文件上传失败, 错误信息: " + e.getMessage());
        }
    }

}
